package longcaisuyun.longcai.com.yiliubabalongcaisuyun;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.yun.YunAction;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.InstrumentedActivity;
import cn.jpush.android.api.TagAliasCallback;
import longcaisuyun.longcai.com.fragment.frag_main_dingdanguanli;
import longcaisuyun.longcai.com.fragment.frag_main_own;
import longcaisuyun.longcai.com.fragment.frag_main_qiangdan;
import longcaisuyun.longcai.com.fragment.frag_main_shop;
import longcaisuyun.longcai.com.mystatic.publicstatic;
import longcaisuyun.longcai.com.net.PostQiangList;
import longcaisuyun.longcai.com.utils.ExampleUtil;
import wh.database.KJDB;
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                            O\ = /O
//                        ____/`---'\____
//                      .   ' \\| |// `.
//                       / \\||| : |||// \
//                     / _||||| -:- |||||- \
//                       | | \\\ - /// | |
//                     | \_| ''\---/'' | |
//                      \ .-\__ `-` ___/-. /
//                   ___`. .' /--.--\ `. . __
//                ."" '< `.___\_<|>_/___.' >'"".
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |
//                 \ \ `-. \_ __\ /__ _/ .-` / /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//
//         .............................................
//         佛祖保佑             永无BUG
//         佛曰:
//                  写字楼里写字间，写字间里程序员；
//                  程序人员写程序，又拿程序换酒钱。
//                  酒醒只在网上坐，酒醉还来网下眠；
//                  酒醉酒醒日复日，网上网下年复年。
//                  但愿老死电脑间，不愿鞠躬老板前；
//                  奔驰宝马贵者趣，公交自行程序员。
//                  别人笑我忒疯癫，我笑自己命太贱；
//                  不见满街漂亮妹，哪个归得程序员？
/************************************************************/
//

/************************************************************/

public class MainActivity extends InstrumentedActivity implements View.OnClickListener {

    ImageView iv1, iv2, iv3, iv4;
    TextView tv1, tv2, tv3, tv4;
    FrameLayout frame_main;
    LinearLayout l_1, l_2, l_3, l_4;
    frag_main_dingdanguanli f_dingdanguanli;
    frag_main_own f_own;
    frag_main_qiangdan f_qiangdan;
    frag_main_shop f_shop;
    List<Fragment> list = new ArrayList<Fragment>();
    FragmentManager fm_main = MainActivity.this.getFragmentManager();
    Fragment mContent;
    Handler mHandler;
    private KJDB kjdb;
    public static boolean daoJiShi = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View view = getWindow().getDecorView();
        // 适配工具将视图重新排布
        MyApplication.ScaleScreenHelper.loadView((ViewGroup) view);
        ViewInit();
        kjdb = MyApplication.kjdb;
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_SET_ALIAS:
                        Log.e("我是tag", (String) msg.obj);
//                        JPushInterface.setAliasAndTags(MainActivity.this,
//                                (String) msg.obj, null, mAliasCallback);
                        break;

                    case MSG_SET_TAGS:
                        Log.e("我是tagMSG_SET_TAGS", (String) msg.obj);
//                        JPushInterface.setAliasAndTags(MainActivity.this,
//                                null, (Set<String>) msg.obj, mTagsCallback);
                        break;

                    default:

                }
            }
        };

        YunAction.getInstance().initia(MainActivity.this, new ECDevice.InitListener() {

            @Override
            public void onInitialized() {

                YunAction.getInstance().setYunCallBack(new YunAction.YunCallBack() {

                    @Override
                    public void connError() {

                    }

                    @Override
                    public void loginSucceed() {

                    }

                    @Override
                    public void otherLogin() {

                        //new AlertDialog.Builder(MyApplication.INSTANCE.currentActivity()).setTitle("您的账号已在其他设备登录").create().show();
                        //    Toast.makeText(MainActivity.this, "您的账号已在其他设备登录", Toast.LENGTH_SHORT).show();


                        // 创建构建器
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        // 设置参数
                        builder.setTitle("您的账号已在其他设备登录")

                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    // 积极

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        dialog.dismiss();

                                        MyApplication.myPreferences.clearAll();
                                        MainActivity.tuiChu.tuiChu();
//                MyApplication.getInstance().finishActivity();
                                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                                        startActivity(intent);
                                    }
                                });
                        builder.create().show();
                    }

                    @Override
                    public void onReceivedMessage(ECMessage ecMessage) {

                        if (ecMessage.getType() == ECMessage.Type.TXT) {

                            ECTextMessageBody body = (ECTextMessageBody) ecMessage.getBody();

                            int type = 0;

                            try {

                                JSONObject jsonObject = new JSONObject(body.getMessage());

                                type = jsonObject.optInt("type");

                                if (type == 1) {

                                    if (!publicstatic.sijiType.equals("1") ||
                                            !jsonObject.optString("cityid").equals(MyApplication.myPreferences.readCityid()) ||
                                            !jsonObject.optString("carid").equals(MyApplication.myPreferences.readCarId()) ||
                                            AMapUtils.calculateLineDistance(new LatLng(Double.valueOf(jsonObject.optString("weidu")), Double.valueOf(jsonObject.optString("jingdu"))), new LatLng(MyApplication.loc.getLatitude(), MyApplication.loc.getLongitude())) > Float.valueOf(MyApplication.myPreferences.readjuli()) * 1000) {

                                        return;

                                    }

                                    HttpPost(jsonObject);

                                } else if (type == 2) {

                                    Intent i = new Intent(MainActivity.this, DingResultActivity.class);
                                    i.putExtra("orderid", jsonObject.getString("orderid"));
                                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(i);

                                }

                            } catch (Exception e) {

                                e.printStackTrace();

                            }

                        }

                    }

                });

                if (!MyApplication.myPreferences.readUid().equals("")) {

                    YunAction.getInstance().login(MainActivity.this, MyApplication.myPreferences.readUid());

                }

            }

            @Override
            public void onError(Exception e) {

            }

        });

    }

    private void ViewInit() {
        f_dingdanguanli = new frag_main_dingdanguanli();
        f_own = new frag_main_own();
        f_qiangdan = new frag_main_qiangdan();
        f_qiangdan.setHand(handler);
        f_shop = new frag_main_shop();
        list.add(f_qiangdan);
        list.add(f_dingdanguanli);
        list.add(f_shop);
        list.add(f_own);
        f_own.exit(new frag_main_own.Exit() {
            @Override
            public void appexit() {
//                int currentVersion = android.os.Build.VERSION.SDK_INT;
//                if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
//                    Intent startMain = new Intent(Intent.ACTION_MAIN);
//                    startMain.addCategory(Intent.CATEGORY_HOME);
//                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(startMain);
//                    System.exit(0);
//                } else {// android2.1
//                    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//                    am.restartPackage(getPackageName());
//                }
                finish();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });
        frame_main = (FrameLayout) findViewById(R.id.fram);
        iv1 = (ImageView) findViewById(R.id.imageView);
        iv2 = (ImageView) findViewById(R.id.imageView2);
        iv3 = (ImageView) findViewById(R.id.imageView3);
        iv4 = (ImageView) findViewById(R.id.imageView4);
        tv1 = (TextView) findViewById(R.id.textView);
        tv2 = (TextView) findViewById(R.id.textView2);
        tv3 = (TextView) findViewById(R.id.textView3);
        tv4 = (TextView) findViewById(R.id.textView4);
        l_1 = (LinearLayout) findViewById(R.id.l_1);
        l_2 = (LinearLayout) findViewById(R.id.l_2);
        l_3 = (LinearLayout) findViewById(R.id.l_3);
        l_4 = (LinearLayout) findViewById(R.id.l_4);
        l_1.setOnClickListener(this);
        l_2.setOnClickListener(this);
        l_3.setOnClickListener(this);
        l_4.setOnClickListener(this);
        tuiChu = new tuiChu() {
            @Override
            public void tuiChu() {
                finish();
            }
        };
        addFragment();
        onClick(l_1);

    }

    private void addFragment() {
        FragmentManager fm_main = MainActivity.this.getFragmentManager();
        FragmentTransaction fm_transaction = fm_main.beginTransaction();
        fm_transaction.add(R.id.fram, f_qiangdan);
        mContent = list.get(0);
        fm_transaction.commit();
    }


    public void switchContent(Fragment to) {
        if (mContent != to) {
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(mContent).add(R.id.fram, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(mContent).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }

    }

    @Override
    public void onClick(View v) {
        setDefault();
        switch (v.getId()) {

            case R.id.l_1:
                tv1.setTextColor(Color.parseColor("#75cde6"));
                iv1.setBackground(getResources().getDrawable(R.mipmap.qiangdan2));
//                switchFrag(0);
                switchContent(list.get(0));
                break;
            case R.id.l_2:
                tv2.setTextColor(Color.parseColor("#75cde6"));
                iv2.setBackground(getResources().getDrawable(R.mipmap.dingdanguanli2));
//                switchFrag(1);
                switchContent(list.get(1));
                frag_main_dingdanguanli dingdanguanli = new frag_main_dingdanguanli();
                dingdanguanli.shuaXin();
                break;
            case R.id.l_3:
                tv3.setTextColor(Color.parseColor("#75cde6"));
                iv3.setBackground(getResources().getDrawable(R.mipmap.maichang2));
//                switchFrag(2);
                switchContent(list.get(2));
                frag_main_shop frag_main_shop = new frag_main_shop();
                frag_main_shop.change();
                break;
            case R.id.l_4:
                tv4.setTextColor(Color.parseColor("#75cde6"));
                iv4.setBackground(getResources().getDrawable(R.mipmap.wode2));
//                switchFrag(3);
                switchContent(list.get(3));
                break;

        }
    }

    public void setDefault() {
        tv1.setTextColor(Color.parseColor("#848481"));
        iv1.setBackgroundResource(R.mipmap.qiangdan1);
        tv2.setTextColor(Color.parseColor("#848481"));
        iv2.setBackgroundResource(R.mipmap.dingdanguanli1);
        tv3.setTextColor(Color.parseColor("#848481"));
        iv3.setBackgroundResource(R.mipmap.maichang1);
        tv4.setTextColor(Color.parseColor("#848481"));
        iv4.setBackgroundResource(R.mipmap.wode1);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); // 调用双击退出函数
        }
        return false;
    }

    public static tuiChu tuiChu;

    public static interface tuiChu {
        void tuiChu();
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {

                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
            System.exit(0);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    setTag();
                    registerMessageReceiver();
//                    JPushInterface.init(MainActivity.this);
//                    JPushInterface.resumePush(MainActivity.this);

                    break;
                case 1:

//                    JPushInterface.stopPush(MainActivity.this);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
//        if (!JPushInterface.isPushStopped(MainActivity.this)) {
//            JPushInterface.resumePush(MainActivity.this);
//        }

    }

    private void setTag() {

        Set<String> tagSet = new LinkedHashSet<String>();
        tagSet.add("7");
        // 调用JPush API设置Tag
//        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, tagSet));
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, MyApplication.myPreferences.readUid()));
    }

    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {
        private String orderid;
        private String action = "longcaisuyun.com.yiliubabalongcaisuyun.dele";
        private Runnable runnable;
        private Handler handler;

        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {

                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);

                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                try {
                    // Toast.makeText(MainActivity.this, "" + extras, Toast.LENGTH_SHORT).show();
                    final JSONObject jsonObject = new JSONObject(extras);
                    Log.e("wefwf", jsonObject.getString("orderid"));
                    orderid = jsonObject.getString("orderid");
                    if (jsonObject.getString("type").equals("1")) {
                        HttpPost(jsonObject);
//                        HttpPostTest(orderid);
                    }


                    if (jsonObject.getString("type").equals("2")) {
                        Intent i = new Intent(context, DingResultActivity.class);
                        i.putExtra("orderid", jsonObject.getString("orderid"));
                        //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(i);
                    }

                } catch (Exception e) {
                }

            }
        }

    }

    private void HttpPost(JSONObject jsonObject) {
        f_qiangdan.reflash();
        try {
            new PostQiangList(MyApplication.myPreferences.readUid(), jsonObject.getString("orderid"), new AsyCallBack<PostQiangList.Info>() {
                @Override
                public void onSuccess(String toast, int type, PostQiangList.Info info) throws Exception {
                    Toast.makeText(MainActivity.this, "有新订单", Toast.LENGTH_SHORT).show();
//                        System.out.println("info.message 状态是多少" + info.message);
                    if (info.message.equals("2")) {
                        publicstatic.qingShiShiDingDan = true;
                    }
                    f_qiangdan.initData_1(info.list);
                    f_qiangdan.initData();
                    startMp3();
                }

                @Override
                public void onFail(String toast, int type) throws Exception {
                    System.out.println("失败了 ,哈哈哈哈哈");
                    super.onFail(toast, type);
                }
            }).execute(MainActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private MediaPlayer mediaPlayer;

    private void startMp3() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
        mediaPlayer = MediaPlayer.create(this, R.raw.ring);
        mediaPlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            Log.e("我是codemTagsCallback", code + "");
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";

                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";

                    if (ExampleUtil.isConnected(MainActivity.this)) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_TAGS, tags),
                                1000 * 60);
                    } else {

                    }
                    break;

            }

        }

    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            Log.e("我是codem mAliasCallback", code + "");
            switch (code) {
                case 0:

                    break;

                case 6002:

                    if (ExampleUtil.isConnected(MainActivity.this)) {
                        mHandler.sendMessageDelayed(
                                mHandler.obtainMessage(MSG_SET_ALIAS, alias),
                                1000 * 60);
                    } else {

                    }
                    break;

            }

        }

    };
    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

}
